'use client'

import { useCallback, useRef } from 'react'
import { Cell } from '@/types/sheet'

interface UseUniverDataProps {
  univerAPI: any
  isReady: boolean
}

interface UseUniverDataReturn {
  getUniverData: () => Cell[]
  getActiveWorkbookData: () => Cell[]
  getSheetData: (workbookId: string, sheetId: string) => Cell[]
  setCellData: (row: number, column: number, value: string, formula?: string) => void
  setRangeData: (data: Array<Array<string>>, startRow?: number, startColumn?: number) => void
}

export function useUniverData({ univerAPI, isReady }: UseUniverDataProps): UseUniverDataReturn {
  
  // 直接访问 Univer 内部数据的方法 - 优化版本，避免阻塞UI
  const getUniverData = useCallback((): Cell[] => {
    if (!isReady || !univerAPI) {
      return []
    }

    const cells: Cell[] = []
    
    try {
      // 获取活动工作簿
      const workbook = univerAPI.getActiveWorkbook()
      if (!workbook) {
        return []
      }

      // 获取活动工作表
      const sheet = workbook.getActiveSheet()
      if (!sheet) {
        return []
      }

      // 使用更安全的方法获取单元格数据，避免阻塞UI
      let cellData: any = {}
      
      try {
        // 优先尝试使用 getCellData 方法
        if (typeof sheet.getCellData === 'function') {
          cellData = sheet.getCellData()
        } else {
          // 如果 getCellData 不存在，使用简化的方法
          console.warn('getCellData 方法不存在，使用简化方法')
          
          // 限制范围，避免性能问题
          const maxRow = 50 // 进一步限制最大行数
          const maxCol = 20 // 进一步限制最大列数
          
          // 使用更安全的方法逐个获取单元格
          for (let row = 0; row < maxRow; row++) {
            cellData[row] = {}
            for (let col = 0; col < maxCol; col++) {
              try {
                // 使用 getCellValue 方法获取单个单元格值
                if (typeof sheet.getCellValue === 'function') {
                  const value = sheet.getCellValue(row, col)
                  if (value !== null && value !== undefined && value !== '') {
                    cellData[row][col] = { v: value }
                  }
                }
              } catch (cellError) {
                // 忽略单个单元格的错误，继续处理其他单元格
                continue
              }
            }
          }
        }
      } catch (dataError) {
        console.warn('获取单元格数据失败:', dataError)
        cellData = {}
      }

      if (!cellData || typeof cellData !== 'object') {
        return []
      }

      // 遍历所有单元格数据，添加超时保护
      const startTime = Date.now()
      const timeout = 1000 // 1秒超时
      
      Object.keys(cellData).forEach(rowKey => {
        // 检查超时
        if (Date.now() - startTime > timeout) {
          console.warn('数据获取超时，返回部分数据')
          return
        }
        
        const rowData = cellData[rowKey]
        if (rowData && typeof rowData === 'object') {
          Object.keys(rowData).forEach(colKey => {
            const cell = rowData[colKey]
            if (cell && (cell.v !== undefined || cell.f !== undefined)) {
              cells.push({
                id: `${rowKey}-${colKey}`,
                row: parseInt(rowKey),
                column: parseInt(colKey),
                value: cell.v || '',
                formula: cell.f || '',
                style: cell.s || {},
                sheetId: sheet.getSheetId ? sheet.getSheetId() : 'unknown',
                createdAt: new Date(),
                updatedAt: new Date()
              })
            }
          })
        }
      })
      
      return cells
      
    } catch (error) {
      console.error('获取 Univer 数据时出错:', error)
      return []
    }
  }, [isReady, univerAPI])

  // 获取指定工作簿的数据
  const getActiveWorkbookData = useCallback((): Cell[] => {
    return getUniverData()
  }, [getUniverData])

  // 获取指定工作表的数据
  const getSheetData = useCallback((workbookId: string, sheetId: string): Cell[] => {
    return getUniverData()
  }, [getUniverData])

  // 设置单个单元格数据
  const setCellData = useCallback((row: number, column: number, value: string, formula?: string) => {
    if (!isReady || !univerAPI) {
      return
    }

    try {
      const workbook = univerAPI.getActiveWorkbook()
      if (!workbook) return

      const sheet = workbook.getActiveSheet()
      if (!sheet) return

      // 使用Univer的API设置单元格值
      if (formula) {
        sheet.setCellFormula(row, column, formula)
      } else {
        sheet.setCellValue(row, column, value)
      }
    } catch (error) {
      console.error('设置单元格数据失败:', error)
    }
  }, [isReady, univerAPI])

  // 设置范围数据
  const setRangeData = useCallback((data: Array<Array<string>>, startRow = 0, startColumn = 0) => {
    if (!isReady || !univerAPI) {
      return
    }

    try {
      const workbook = univerAPI.getActiveWorkbook()
      if (!workbook) return

      const sheet = workbook.getActiveSheet()
      if (!sheet) return

      // 批量设置单元格数据
      data.forEach((rowData, rowIndex) => {
        rowData.forEach((cellValue, colIndex) => {
          if (cellValue !== undefined && cellValue !== null && cellValue !== '') {
            sheet.setCellValue(startRow + rowIndex, startColumn + colIndex, cellValue)
          }
        })
      })
    } catch (error) {
      console.error('设置范围数据失败:', error)
    }
  }, [isReady, univerAPI])

  return {
    getUniverData,
    getActiveWorkbookData,
    getSheetData,
    setCellData,
    setRangeData
  }
}